package cl.usm.acceso.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import cl.usm.acceso.bean.ServicioBean;

public class ServicioDAO {

	private int idServicio;
	private String descripcion;
	
	public int getIdServicio() {
		return idServicio;
	}

	public void setIdServicio(int idServicio) {
		this.idServicio = idServicio;
	}

	public String getDescripcion() {
		return descripcion;
	}

	public void setDescripcion(String descripcion) {
		this.descripcion = descripcion;
	}

	public int seleccionar(int idServicio) {
		int result = -1;
		setIdServicio(idServicio);
		try {
			InitialContext context = new InitialContext();
			DataSource dataSource = (DataSource) context.lookup("jdbc/Lavasoft");
			
			Connection connection = dataSource.getConnection();
			Statement statement = connection.createStatement();
			String sql = "Select descripcion from servicio where idServicio = '" + idServicio + "'";
	
			ResultSet resultSet = statement.executeQuery(sql);
			
			while (resultSet.next()) {
				setDescripcion(resultSet.getString("descripcion"));
			}
	
			resultSet.close();
			statement.close();
			connection.close();
			result = 1;
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;		
	}
	
	public List<ServicioBean> getListaServicios() {
		
		List<ServicioBean> list = new ArrayList<ServicioBean>();
		
		try {
			InitialContext context = new InitialContext();
			DataSource dataSource = (DataSource) context.lookup("jdbc/Lavasoft");
			
			Connection connection = dataSource.getConnection();
			Statement statement = connection.createStatement();
			String query = "Select idServicio, descripcion from servicio";
	
			ResultSet resultSet = statement.executeQuery(query);
	
			while (resultSet.next()) {
				ServicioBean item = new ServicioBean();
				item.setIdServicio(resultSet.getInt("idServicio"));
				item.setDescripcion(resultSet.getString("descripcion"));
				list.add(item);
			}
	
			resultSet.close();
			statement.close();
			connection.close();
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
